package com.contextor.magiccards.dao.battle.impl;

import com.contextor.magiccards.dao.BaseDao;
import com.contextor.magiccards.dao.battle.BattleDao;
import com.contextor.magiccards.dao.utils.CollectionUtils;
import com.contextor.magiccards.dao.utils.Pager;
import com.contextor.magiccards.model.battle.Battle;
import com.contextor.magiccards.model.battle.BattleStatus;
import com.contextor.magiccards.model.character.Personage;
import com.contextor.magiccards.model.user.User;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Repository;

import java.sql.SQLException;
import java.util.List;

/**
 * User: Sergey
 * Date: 20.03.2011 11:54:44
 */
@Repository
class BattleDaoImpl extends BaseDao<Battle, Integer> implements BattleDao {
    public BattleDaoImpl() {
        super(Battle.class);
    }

    public Battle findWithStatus(final User user, final BattleStatus status) {
        return (Battle) this.getHibernateTemplate().execute(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("SELECT b from Battle b " +
                        " WHERE b.user.id = :userId" +
                        " AND b.status = :status")
                        .setString("userId", user.getId())
                        .setParameter("status", status)
                        .uniqueResult();
            }
        });
    }

    public List<Battle> findWithStatus(final int shard, final String uid, final BattleStatus status, final Pager pager,
                                       final Personage personage) {
        return CollectionUtils.toList(this.getHibernateTemplate().executeFind(new HibernateCallback<Object>() {
            public Object doInHibernate(Session session) throws HibernateException, SQLException {
                return session.createQuery("SELECT b FROM Battle b" +
                        " INNER JOIN FETCH b.user  " +
                        " INNER JOIN FETCH b.firstPlayer  " +
                        " WHERE b.status = :status " +
                        " AND b.level = :level " +
                        " AND b.user.uid != :userId " +
                        " ORDER BY b.id DESC")
                        .setParameter("status", status)
                        .setInteger("level", personage.getLevel())
                        .setString("userId", uid)
                        .setFirstResult(pager.from())
                        .setMaxResults(pager.till())
                        .list();
            }
        }));
    }
}
